<template>
  <div class="main">
    <h4>填写申请信息</h4>
    <el-form :model="form" label-width="100px" style="width: 400px;">
      <el-form-item label="老人姓名" prop="elderlyId">
        <el-select 
          v-model="form.elderlyId" 
          placeholder="请选择老人" 
          @change="handleElderlyChange"
          @visible-change="handleElderlySelectVisible"
        >
          <el-input 
            v-model="elderlySearchKey" 
            placeholder="搜索老人姓名..." 
            clearable 
            size="small"
            class="elderly-search-input" 
            @input="handleElderlySearch" 
            @keyup.enter="handleElderlySearch" 
          />
          <el-option-group label="老人列表">
            <el-option 
              v-for="dict in elderlyList" 
              :key="dict.id" 
              :label="dict.name" 
              :value="dict.id"
            ></el-option>
            <!-- 下拉框分页按钮 -->
            <div class="select-pagination" v-if="elderlyTotal > 0">
              <el-button 
                style="width: 45px; height: 30px;" 
                icon="el-icon-arrow-left"
                @click="changeElderlyPage(currentElderlyPage - 1)" 
                :disabled="currentElderlyPage === 1"
              >上一页</el-button>
              <span class="page-info">
                {{ currentElderlyPage }} / {{ totalElderlyPages }}
              </span>
              <el-button 
                style="width: 45px; height: 30px;" 
                icon="el-icon-arrow-right"
                @click="changeElderlyPage(currentElderlyPage + 1)"
                :disabled="currentElderlyPage >= totalElderlyPages"
              >下一页</el-button>
            </div>
          </el-option-group>
        </el-select>
      </el-form-item>
      <el-form-item label="老人身份证号" prop="idCard">
        <el-input v-model="form.idCard" :disabled="true" placeholder="老人身份证号" />
      </el-form-item>
      <el-form-item label="联系方式" prop="contact">
        <el-input v-model="form.contact" :disabled="true" placeholder="联系方式" />
      </el-form-item>
      <el-form-item label="费用期限" prop="feeTerm">
        {{ formatTimeToDate2(form.feeStartTerm) }} -- {{ formatTimeToDate2(form.feeEndTerm) }}
      </el-form-item>
      <el-form-item label="护理等级" prop="nursingLevel">
        <el-input v-model="form.nursingLevel" :disabled="true" placeholder="护理等级" />
      </el-form-item>
      <el-form-item label="入住床位" prop="bed">
        <el-input v-model="form.bed" :disabled="true" placeholder="入住床位" />
      </el-form-item>
      <el-form-item label="签约合同" prop="contract">
        <el-input v-model="form.contract" :disabled="true" placeholder="签约合同" />
      </el-form-item>
      <el-form-item label="养老顾问" prop="elderAdvisor">
        <el-input v-model="form.elderAdvisor" :disabled="true" placeholder="养老顾问" />
      </el-form-item>
      <el-form-item label="护理员" prop="nursingStaff">
        <div class="nursing-staff-tags">
          <el-tag 
            style="margin-right: 20px;" 
            v-for="(staff, index) in form.nursingStaff" 
            :key="index" 
            type="info"
            size="small"
          >
            {{ staff.nickName }}
          </el-tag>
          <span v-if="!form.nursingStaff || form.nursingStaff.length === 0" class="empty-tip">
            暂无护理员
          </span>
        </div>
      </el-form-item>
    </el-form>
  </div>
  <div class="footer">
    <h4>申请信息</h4>
    <el-form :model="leaveForm" label-width="100px" style="width: 400px;">
      <el-form-item label="退住日期" prop="checkoutDate" required>
        <el-date-picker 
          v-model="leaveForm.checkoutDate" 
          :disabled-date="disablePastDates" 
          type="date"
          placeholder="选择退住日期" 
          style="width: 100%;" 
        />
      </el-form-item>
      <el-form-item label="退住原因" prop="checkoutReason" required>
        <el-select v-model="leaveForm.checkoutReason" placeholder="请选择">
          <el-option label="身体康复" value="身体康复" />
          <el-option label="转院" value="转院" />
          <el-option label="家庭原因" value="家庭原因" />
          <el-option label="其他" value="其他" />
        </el-select>
      </el-form-item>
      <el-form-item label="备注" prop="remark">
        <el-input 
          v-model="leaveForm.remark" 
          type="textarea" 
          placeholder="请输入" 
          :maxlength="100" 
          show-word-limit 
        />
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup>
import { ref, reactive, getCurrentInstance } from 'vue';
import { listElderly, getElderlyAll } from "@/api/le/elderly"
import { useUserStore } from '@/store/modules/user'
import { listCheckoutmanagement, addCheckoutmanagement } from "@/api/le/checkoutmanagement"
import { listRequest } from "@/api/le/request";
import { listPendingTasks } from "@/api/le/pendingTasks";
import { useRouter } from "vue-router";
// 获取路由实例
const router = useRouter();


// 组件实例与工具
const { proxy } = getCurrentInstance()
const emit = defineEmits(['updateSubmitForm']);
const userStore = useUserStore() // 登录用户信息

// 老人下拉框核心变量
const elderlySearchKey = ref('') // 搜索关键词
const elderlyList = ref([]) // 当前页显示的老人列表
const filteredAllElderly = ref([]) // 筛选后的全部老人（未退住+未请假）
const elderlyTotal = ref(0) // 搜索后的总条数
const currentElderlyPage = ref(1) // 当前页码
const elderlyPageSize = ref(10) // 每页显示条数
const totalElderlyPages = ref(0) // 总页数
const isBtnDisabled = ref(false) // 按钮禁用状态

// 表单数据
const form = reactive({
  elderlyId: '',
  elderName: '',
  idCard: '',
  contact: '',
  feeStartTerm: '',
  feeEndTerm: '',
  nursingLevel: '',
  checkInManagement: {},
  bed: '',
  creator: userStore.nickName,
  contract: '',
  checkoutManagementId: '',
  elderAdvisor: '',
  nursingStaff: [],
  pending: {}
});

const leaveForm = reactive({
  checkoutDate: '',
  checkoutReason: '',
  remark: ''
});

const submitForm = reactive({})

/** 初始化：加载所有老人并筛选（排除退住和请假） */
const initFilteredElderly = () => {
  // 1. 加载所有老人（不分页）
  listElderly({
    pageNum: 1,
    pageSize: 9999, // 一次性获取全部
    name: ''
  }).then(elderlyRes => {
    const allElderly = elderlyRes.rows || [];

    // 2. 获取退住老人ID
    listCheckoutmanagement({ pageSize: 1000 }).then(checkoutRes => {
      const checkoutIds = new Set(
        checkoutRes.rows.map(order => order.elderlyId).filter(Boolean)
      );

      // 3. 获取请假中老人ID
      listRequest({ pageSize: 1000, leaveStatus: "请假中" }).then(leaveRes => {
        const leaveIds = new Set(
          leaveRes.rows.map(leave => leave.elderlyId).filter(Boolean)
        );

        // 4. 筛选：排除退住和请假的老人
        filteredAllElderly.value = allElderly.filter(elderly => 
          !checkoutIds.has(elderly.id) && !leaveIds.has(elderly.id)
        );

        // 初始化后显示第一页
        handleElderlySearch();
      });
    }).catch(err => {
      console.error("获取退住订单失败：", err);
    });
  }).catch(err => {
    console.error("获取老人列表失败：", err);
  });
};

/** 老人姓名模糊搜索（前端筛选） */
const handleElderlySearch = () => {
  currentElderlyPage.value = 1; // 重置页码
  updateElderlyListByPage();
};

/** 根据页码和搜索词更新当前页列表 */
const updateElderlyListByPage = () => {
  // 1. 前端模糊搜索
  let searchedList = filteredAllElderly.value;
  if (elderlySearchKey.value) {
    const key = elderlySearchKey.value.trim().toLowerCase();
    searchedList = searchedList.filter(elderly => 
      elderly.name.toLowerCase().includes(key)
    );
  }

  // 2. 计算分页参数
  elderlyTotal.value = searchedList.length;
  totalElderlyPages.value = Math.ceil(elderlyTotal.value / elderlyPageSize.value);

  // 3. 截取当前页数据
  const start = (currentElderlyPage.value - 1) * elderlyPageSize.value;
  const end = start + elderlyPageSize.value;
  elderlyList.value = searchedList.slice(start, end);
};

/** 切换分页 */
const changeElderlyPage = (page) => {
  if (page < 1 || page > totalElderlyPages.value) return;
  currentElderlyPage.value = page;
  updateElderlyListByPage();
};

/** 下拉框显示/隐藏时刷新 */
const handleElderlySelectVisible = (visible) => {
  if (visible) {
    updateElderlyListByPage();
  }
};

/** 选择老人后加载详情 */
const handleElderlyChange = (elderlyId) => {
  if (!elderlyId) {
    // 清空表单
    Object.assign(form, {
      elderName: '', idCard: '', contact: '', feeStartTerm: '', feeEndTerm: '',
      nursingLevel: '', checkInManagement: {}, bed: '', elderAdvisor: '', nursingStaff: []
    });
    return;
  }

  // 加载老人详情
  getElderlyAll(elderlyId).then(response => {
    const data = response.data || {};
    form.checkInManagement = data.checkInManagement || {};
    form.feeStartTerm = form.checkInManagement.feeStartDate || '';
    form.feeEndTerm = form.checkInManagement.feeEndDate || '';
    form.nursingLevel = (data.nursingLevelYyh || {}).levelName || '';
    form.bed = (data.bed || {}).bedNo || '';
    form.contract = (data.contract || {}).contractName || '';
    form.elderAdvisor = (data.sysUser && data.sysUser[0]) ? data.sysUser[0].nickName : '';
    form.nursingStaff = data.sysUser || [];
    
    // 提交表单预填数据
    submitForm.bedId = (data.bed || {}).id;
    submitForm.elderlyName = data.name || '';

    // 填充基础信息
    const selected = filteredAllElderly.value.find(item => item.id === elderlyId);
    if (selected) {
      form.elderName = selected.name || '';
      form.idCard = selected.idCard || '';
      form.contact = selected.contact || '';
    }
  });
};

/** 提交退住申请 */
const handleSubmit = () => {
  submitForm.elderlyId = form.elderlyId;
  submitForm.checkInManagementId = form.checkInManagement.id;
  submitForm.checkOutReason = leaveForm.checkoutReason;
  submitForm.remark = leaveForm.remark;
  submitForm.checkOutDate = leaveForm.checkoutDate;
  submitForm.creator = userStore.id;
  submitForm.isDeleted = 0;

  addCheckoutmanagement(submitForm).then(response => {
    proxy.$modal.msgSuccess("提交成功");
    form.checkoutManagementId = response.data;

    // 获取待办任务
    listPendingTasks({ 
      bussniessId: form.checkoutManagementId, 
      assigneeId: userStore.id, 
      idHandle: 0 
    }).then(res => {
      form.pending = res.rows[0] || {};
      emit('updateSubmitForm', { ...form, ...leaveForm });

        router.push({ path: "/xietong/pendingTasks", 
             });
    });
  });
};

/** 禁用过去的日期 */
const disablePastDates = (time) => {
  return time.getTime() < new Date().setHours(0, 0, 0, 0);
};

/** 日期格式化 */
const formatTimeToDate2 = (timeStr) => {
  if (!timeStr) return '暂无数据';
  const date = new Date(timeStr);
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  return `${year}-${month}-${day}`;
};

/** 暴露方法给父组件 */
defineExpose({
  handleSubmit,
  setBtnDisabled: (status) => { isBtnDisabled.value = status; }
});

// 初始化筛选老人列表
initFilteredElderly();
</script>

<style scoped>
.main, .footer {
  width: 100%;
  padding: 10px 20px;
  margin-bottom: 20px;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.footer {
  height: auto;
  min-height: 400px;
}

.elderly-search-input {
  margin-bottom: 10px;
  width: 100%;
}

.select-pagination {
  display: flex;
  align-items: center;
  justify-content: center;
  margin-top: 10px;
  gap: 10px;
}

.page-info {
  color: #666;
  font-size: 12px;
}

.nursing-staff-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.empty-tip {
  color: #999;
  font-size: 14px;
}
</style>